package com.isunland.managesystem.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.isunland.managesystem.R;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.utils.FUtils;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import java.io.Serializable;
import java.util.HashMap;

/**
 * ListFragment基础类,封装了 1. 联网.下拉刷新 2. 错误页面,空页面
 */

@SuppressLint("InflateParams") public abstract class BaseListFragment
    extends PullToRefreshListFragment implements OnRefreshListener<ListView> {

  public static final int SHOW_ADAPTER_VIEW = 2;
  public static final int SHOW_LOADING_VIEW = 3;
  public static final int TYPE_NETWORKError = 0;
  public static final int TYPE_SEREVERError = 1;
  public static final int TYPE_SEREVER_DATA_Error = 2;
  public static final int TYPE_TIME_OUT_ERROR = 3;
  public static final int SHOW_ERROR_VIEW = 0;
  public static final int SHOW_EMPTY_VIEW = 1;
  public PullToRefreshListView mPullRefreshListView;
  public ListView mListview;
  public View mErrorView;
  public View mEmptyView;
  public BaseParams mBaseParams;
  public CurrentUser mCurrentUser;
  protected BaseVolleyActivity mActivity;
  private int mCurrentPage = 1;// 请求第几页的数据.
  private View mLoadingView;
  private TextView mTvErrorHint;
  private View mFabBgView;
  private FloatingActionMenu mFamMenu;
  private FUtils mFutils;
  private boolean mIsPaging;
  /** 是否禁用volley */
  private boolean mIsForbiddenVolley;

  public static Fragment newInstance(BaseParams params, Fragment fragment) {
    Bundle args = new Bundle();
    args.putSerializable(BaseFragment.EXTRA_PARAMS, params);
    fragment.setArguments(args);
    return fragment;
  }

  public boolean isForbiddenVolley() {
    return mIsForbiddenVolley;
  }

  public void setIsForbiddenVolley(boolean mIsForbiddenVolley) {
    this.mIsForbiddenVolley = mIsForbiddenVolley;
  }

  public PullToRefreshListView getPullRefreshListView() {
    return mPullRefreshListView;
  }

  public int getCurrentPage() {
    return mCurrentPage;
  }

  public void setCurrentPage(int mCurrentPage) {
    this.mCurrentPage = mCurrentPage;
  }

  public boolean isPaging() {
    return mIsPaging;
  }

  public FloatingActionMenu getFamMenu() {
    return mFamMenu;
  }

  @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {
    Mode mode = refreshView.getCurrentMode();
    //如果分页的话,更改页码,首页清空数据.
    refreshWithMode(mode);
  }

  private void refreshWithMode(Mode mode) {
    if (mode.equals(Mode.PULL_FROM_START)) mCurrentPage = 1;
    if (mode.equals(Mode.PULL_FROM_END)) mCurrentPage++;
    volleyPost();
  }

  public void refreshFromTop() {
    mPullRefreshListView.setMode(Mode.PULL_FROM_START);
    refreshWithMode(mPullRefreshListView.getCurrentMode());
    //还原
    mPullRefreshListView.setMode(mIsPaging ? Mode.BOTH : Mode.PULL_FROM_START);
  }

  /**
   * @return boolean
   */
  protected boolean isForbiddenRefresh() {
    // Auto-generated method stub
    return false;
  }

  public void setTitleCustom(int title) {
    if (title == 0 || mActivity instanceof BasePagerActivity) return;
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setTitle(title);
    }
  }

  public void setTitleCustom(String title) {
    if (TextUtils.isEmpty(title) || mActivity instanceof BasePagerActivity) return;
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setTitle(title);
    }
  }

  public void setBack(boolean hasBack) {

    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setDisplayHomeAsUpEnabled(hasBack);
    }
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {

    mListview = getListView();
    mListview.setVerticalScrollBarEnabled(false);
    mListview.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
    mPullRefreshListView = getPullToRefreshListView();
    //设置刷新标签
    mPullRefreshListView.getLoadingLayoutProxy().setRefreshingLabel("正在载入...");
    //设置下拉标签
    mPullRefreshListView.getLoadingLayoutProxy().setPullLabel("下拉刷新...");
    //设置释放标签
    mPullRefreshListView.getLoadingLayoutProxy().setReleaseLabel("放开以刷新...");
    mPullRefreshListView.setMode(Mode.BOTH);
    //        mPullRefreshListView.getLoadingLayoutProxy().setLoadingDrawable(getActivity().getResources().getDrawable(R.drawable.progress_round));
    mPullRefreshListView.getLoadingLayoutProxy().setLoadingDrawable(null);
    //默认不分页
    mPullRefreshListView.setMode(mIsPaging ? Mode.BOTH : Mode.PULL_FROM_START);
    mPullRefreshListView.setOnRefreshListener(this);
    if (isForbiddenRefresh()) {

      mPullRefreshListView.setMode(Mode.DISABLED);
    }
    floatmenu(view);

    showViewByType(SHOW_LOADING_VIEW);
    isPostStart(true, false);
    initView(view, savedInstanceState);
    super.onViewCreated(view, savedInstanceState);
  }

  private void floatmenu(View view) {
    mFabBgView = view.findViewById(R.id.fab_bg);
    mFamMenu = (FloatingActionMenu) view.findViewById(R.id.fam_menu);
    if (mFabBgView == null || mFamMenu == null) return;
    mFabBgView.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View view) {
        mFamMenu.close(true);
      }
    });
    //floatingActionButton.setMenuButtonColorNormal(Color.parseColor(BaseActivity.accentSkin));
    //floatingActionButton.setMenuButtonColorPressed(fabSkinPressed);

    mFamMenu.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {
      @Override public void onMenuToggle(boolean b) {
        mFutils.revealShow(mFabBgView, b);
      }
    });
  }

  public void setIsPaging(boolean isPaging) {
    mIsPaging = isPaging;
  }

  public void initView(View view, Bundle savedInstanceState) {
    //因为子类可以复写父类的方法,所以initData行为发生改变.mBaseParams可能没有初始化,需要做非空判断
    setTitleCustom(mBaseParams == null ? null : mBaseParams.getTitle());
  }

  public void initData() {
    if (getArguments() != null) {
      Serializable ser = getArguments().getSerializable(BaseFragment.EXTRA_PARAMS);
      if (ser != null && ser instanceof BaseParams) {
        mBaseParams = (BaseParams) ser;
      }
    }
    if (mBaseParams == null) {

      mBaseParams = new BaseParams();
    }
  }

  public void initMockData() {

  }

  /**
   */
  protected void isPostStart(boolean isPostStart, boolean isShowEmpty) {
    if (isPostStart) {
      volleyPost();
    } else {
      if (isShowEmpty) {
        showViewByType(SHOW_EMPTY_VIEW);
      }
    }
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    mActivity = (BaseVolleyActivity) getActivity();
    mCurrentUser = CurrentUser.newInstance(mActivity);
    mFutils = new FUtils();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setDisplayHomeAsUpEnabled(true);
    }
    initData();
    if (MyUtils.isMock()) {
      initMockData();
    }
  }

  public void showViewByType(int type) {
    if (mEmptyView != null) mEmptyView.setVisibility(View.GONE);
    if (mErrorView != null) mErrorView.setVisibility(View.GONE);
    if (mLoadingView != null) mLoadingView.setVisibility(View.GONE);
    View view = null;
    switch (type) {

      case SHOW_LOADING_VIEW:
        view = getLoadingView();

        break;
      case SHOW_ERROR_VIEW:
        view = getErrorView();
        break;
      case SHOW_EMPTY_VIEW:
        view = getEmptyView();

        break;
      case SHOW_ADAPTER_VIEW:

        break;

      default:
        break;
    }
    if (view != null) {

      view.setVisibility(View.VISIBLE);
      mPullRefreshListView.setEmptyView(view);
    }
    setListShown(true);
    if (mPullRefreshListView != null) {

      mPullRefreshListView.onRefreshComplete();
    }
  }

  private View getErrorView() {
    mErrorView = LayoutInflater.from(getActivity()).inflate(R.layout.view_error, null);
    mTvErrorHint = (TextView) mErrorView.findViewById(R.id.tv_empty);

    Button refreshButton = (Button) mErrorView.findViewById(R.id.btn_empty);
    refreshButton.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View arg0) {
        volleyPost();
      }
    });
    return mErrorView;
  }

  /**
   * 更改异常界面提示信息.
   */
  private void setErrorType(int type) {
    if (type == TYPE_NETWORKError) {
      mTvErrorHint.setText(R.string.network_error);
      return;
    }
    if (type == TYPE_SEREVERError) {
      mTvErrorHint.setText(R.string.noConnectionToServer);
      return;
    }
    if (type == TYPE_SEREVER_DATA_Error) {
      mTvErrorHint.setText(R.string.wrong_data);
      return;
    }
    if (type == TYPE_TIME_OUT_ERROR) {
      mTvErrorHint.setText(R.string.timeOutError);
    }
  }

  private View getEmptyView() {
    mEmptyView = LayoutInflater.from(getActivity()).inflate(R.layout.view_empty, null);
    TextView tvEmpty = (TextView) mEmptyView.findViewById(R.id.tv_emptyText_emptyView);
    tvEmpty.setText(setEmptyText());
    return mEmptyView;
  }

  private View getLoadingView() {
    if (mLoadingView == null) {
      mLoadingView = LayoutInflater.from(getActivity()).inflate(R.layout.view_loading, null);
    }
    return mLoadingView;
  }

  /**
   * 空界面显示文字
   */
  protected String setEmptyText() {

    return getString(R.string.that_is_all);
  }

  public void volleyPost() {
    if (mIsForbiddenVolley) return;
    if (!MyUtils.isNetLink(getActivity())) {

      Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_SHORT).show();
      showViewByType(SHOW_ERROR_VIEW);
      setErrorType(TYPE_NETWORKError);
      return;
    }
    if (mPullRefreshListView != null && isRefresh()) {

      mPullRefreshListView.setRefreshing();
    }
    String url = ApiConst.getAbsoluteUrl(getUrl());
    HashMap<String, String> params = getparameters();
    if (mIsPaging) {
      params.put("page", MyStringUtil.valueOf(mCurrentPage));
      params.put("rows", MyStringUtil.valueOf(20));
      params.put("curPage", MyStringUtil.valueOf(mCurrentPage));
      params.put("pageSize", MyStringUtil.valueOf(20));
    }
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) {
        // Auto-generated method stub
        try {

          showViewByType(SHOW_EMPTY_VIEW);

          resolveResponse(arg0);
        } catch (Exception e) {
          LogUtil.e("error=", e);
          showViewByType(SHOW_ERROR_VIEW);
          setErrorType(TYPE_SEREVER_DATA_Error);
        }
      }

      @Override public void onVolleyError(VolleyError error) {
        showViewByType(SHOW_ERROR_VIEW);
        if (error.networkResponse == null) {
          if (error.getClass().equals(TimeoutError.class)) {
            // Show timeout error message

            setErrorType(TYPE_TIME_OUT_ERROR);
          }
        } else {

          setErrorType(TYPE_SEREVERError);
        }
      }

      @Override public boolean ifToastError() {
        // Auto-generated method stub
        return false;
      }
    }, true, isNeedRoleType());
  }

  /**
   * 是否需要人员角色类型,默认是true.
   * false 的时候在基类联网时不传递roleTypeFlag
   *
   * @return true
   */
  public boolean isNeedRoleType() {
    return true;
  }

  public boolean isRefresh() {

    return true;
  }

  /**
   * 获取url
   */
  public abstract String getUrl();

  /**
   * 获取参数列表
   */
  public HashMap<String, String> getparameters() {

    return new HashMap<>();
  }

  /**
   * 解析响应
   */
  public abstract void resolveResponse(String json);

  /**
   * 设置标题
   */

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 响应返回图标
      case android.R.id.home:

        mActivity.finish();
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override protected int setCustomLayoutId() {
    return R.layout.fragment_base_list;
  }

  @Override protected int setCustomtListViewId() {
    return R.id.lv_pullToRefresh;
  }

  @NonNull
  public FloatingActionButton getFloatingActionButton(String text, int imageRes, int colorRes) {
    FloatingActionButton mFabTemp = new FloatingActionButton(mActivity);
    mFabTemp.setLabelText(text);
    mFabTemp.setButtonSize(FloatingActionButton.SIZE_MINI);
    mFabTemp.setImageResource(imageRes);
    mFabTemp.setColorNormalResId(colorRes);
    mFabTemp.setColorPressedResId(colorRes);
    return mFabTemp;
  }

  //public void showDialog(DialogFragment dialog, int requestCode) {
  //  if (dialog == null) return;
  //  dialog.setTargetFragment(this, requestCode);
  //  FragmentManager fm = mActivity.getSupportFragmentManager();
  //  dialog.show(fm, "");
  //}
  public void showDialog(DialogFragment dialog, int requestCode, String tag) {
    if (dialog == null) return;
    if (tag == null) tag = "";
    //当activity不再前台时,会报错.java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

    try {
      dialog.setTargetFragment(this, requestCode);
      FragmentManager fm = mActivity.getSupportFragmentManager();
      dialog.show(fm, tag);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void showLoading(boolean showLoading) {
    mListview.setVisibility(showLoading ? View.GONE : View.VISIBLE);
    mLoadingView.setVisibility(showLoading ? View.VISIBLE : View.GONE);
  }

  public void showDialog(DialogFragment dialog, int requestCode) {
    showDialog(dialog, requestCode, "");
  }

  private void dismissDialog(String tag, Context context) {
    if (context == null) return;
    if (tag == null) tag = "";
    try {
      FragmentManager fm = mActivity.getSupportFragmentManager();
      Fragment dialog = fm.findFragmentByTag(tag);
      if (dialog instanceof DialogFragment) ((DialogFragment) dialog).dismiss();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
